package top.huhuiyu.spirngboot2.total.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import top.huhuiyu.spirngboot2.total.base.BaseDataResult;
import top.huhuiyu.spirngboot2.total.base.BasePageResult;
import top.huhuiyu.spirngboot2.total.base.BaseResult;
import top.huhuiyu.spirngboot2.total.base.PageBean;
import top.huhuiyu.spirngboot2.total.dao.TbNewsDAO;
import top.huhuiyu.spirngboot2.total.entity.TbNews;
import top.huhuiyu.spirngboot2.total.service.NewsService;

import java.util.List;
import java.util.Optional;

@Service
@Slf4j
public class NewsServiceImpl implements NewsService {
    @Autowired
    private TbNewsDAO tbNewsDAO;

    @Override
    public BasePageResult<List<TbNews>> query(PageBean page, TbNews tbNews) {
        // 处理分页
        page = Optional.ofNullable(page).orElse(new PageBean());
        IPage<TbNews> pageinfo = new Page<>(page.getPageNumber(), page.getPageSize());
        // 查询条件
        tbNews = Optional.ofNullable(tbNews).orElse(new TbNews());
        QueryWrapper<TbNews> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("nid", "title", "source", "hits", "lastupdate");
        queryWrapper.like(StringUtils.hasText(tbNews.getTitle()), "title", tbNews.getTitle());
        queryWrapper.like(StringUtils.hasText(tbNews.getSource()), "source", tbNews.getSource());
        pageinfo = tbNewsDAO.selectPage(pageinfo, queryWrapper);
        // 返回查询结果
        return BasePageResult.ok(page.buildPageInfo(pageinfo), pageinfo.getRecords());
    }


    @Override
    public BaseResult add(TbNews tbNews) {
        int r = tbNewsDAO.insert(tbNews);
        log.debug("添加的结果：{},{}", r, tbNews);
        return r == 1 ? BaseResult.ok("添加成功") : BaseResult.fail("添加失败");
    }

    @Override
    public BaseDataResult<TbNews> queryByKey(Integer nid) {
        TbNews tbNews = tbNewsDAO.selectById(nid);
        if (tbNews == null) {
            return BaseDataResult.failNoData("数据查无记录");
        }
        // 更新点击量
        tbNewsDAO.updateHits(nid);
        tbNews.setDeleted(null);
        tbNews.setHits(tbNews.getHits() + 1);
        return BaseDataResult.ok(tbNews);
    }

    @Override
    public BaseResult update(TbNews tbNews) {
        TbNews check = tbNewsDAO.selectById(tbNews.getNid());
        if (check == null) {
            return BaseDataResult.failNoData("数据查无记录");
        }
        tbNewsDAO.updateById(tbNews);
        return BaseResult.ok("修改成功");
    }

    @Override
    public BaseResult delete(Integer nid) {
        tbNewsDAO.deleteById(nid);
        return BaseResult.ok("删除成功");
    }

}
